package com.sirdc.modules.sys.web.OwnerUnit;

import com.sirdc.modules.sys.filter.NodeNewschedulesModel;
import com.sirdc.modules.sys.service.PlanTimeReckonService;
import com.sirdc.modules.utils.ObjectUtils;
import net.huashitong.Project.entity.NewProjects;
import net.huashitong.Project.filter.NewProjectsFilter;
import net.huashitong.Project.service.NewProjectsService;
import net.huashitong.Project.util.HolidayUtils;
import net.huashitong.node.entity.NodeNewschedules;
import net.huashitong.node.entity.NodeNewtemplet;
import net.huashitong.node.filter.NodeNewschedulesFilter;
import net.huashitong.node.service.NodeNewschedulesService;
import net.huashitong.node.service.NodeNewtempletService;
import net.huashitong.nodeFile.controller.UpLoadController;
import net.huashitong.user.entity.BnpUser;
import net.huashitong.user.filter.BnpUserFilter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 业主---待办任务
 * Created by hyp1202 on 2018/7/18.
 */
@Controller
@RequestMapping("/ownerTask")
public class OwnerTaskController {
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");

    @Autowired
    private NodeNewschedulesService nodeNewschedulesService;
    @Autowired
    private NewProjectsService newProjectsService;
    @Autowired
    private NodeNewtempletService nodeNewtempletService;
    @Autowired
    private PlanTimeReckonService planTimeReckonService;

    @ModelAttribute("headType")
    public String returnHeadType() {
        return "业主模块";
    }

    @RequestMapping("/go/list")
    public String getTask(Model model, HttpServletRequest request) throws ParseException {
        model.addAttribute("leftType", "待办任务");
        BnpUser bnpUser = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        if (ObjectUtils.isBlank(bnpUser)) {
            return "/modules/login/login";
        }
        NewProjectsFilter filter = new NewProjectsFilter();
        filter.setUserId(bnpUser.getSysId());
        //根据userId查询管理项目（没有分页）
        List<NewProjects> projectsList = newProjectsService.getProjectInfo3(filter);
        if (projectsList.size() == 0) {
            projectsList = newProjectsService.query();
        }
        Map<String,List<NodeNewschedules>> bigNodeStateNeedMap = new HashMap<>();
        //获取各个项目的大节点
        for (NewProjects projects : projectsList) {
            List<NodeNewschedules> nodeNewschedules = nodeNewschedulesService.getNodeIdsLists("0",projects.getSysId());
            //封装需要的大节点(大节点确认需要Map)
            List<NodeNewschedules> bigNodes = new ArrayList<>();
            for (NodeNewschedules newschedule : nodeNewschedules) {
                if("1".equals(newschedule.getState())){
                    bigNodes.add(newschedule);
                }
            }
            bigNodeStateNeedMap.put(projects.getSysId(),bigNodes);
        }
//        List<NewProjects> projectsList = newProjectsService.getProjectInfo(filter);
        Map<String, List<NodeNewschedules>> nodeNewschedulesMap = new HashMap<>();
        Map<String, NodeNewschedules> bigNodeMap = new HashMap<>();
        List<NodeNewschedules> nodeList = nodeNewschedulesService.getNodeByUser(bnpUser);


        if (projectsList.size() == 0 && nodeList.size() != 0) {
            //征迁单位（不属于业主单位也不属于审批部门）
            Map<String,String> zqProjectMap = new HashMap<>();
            Map<String,NewProjects> projectMap = new HashMap<>();
            List<NewProjects> projects = newProjectsService.query();
            for(NewProjects p : projects){
                if(!projectMap.containsKey(p.getSysId())){
                    projectMap.put(p.getSysId(),p);
                }
            }
            for(NodeNewschedules node : nodeList){
                if(!zqProjectMap.containsKey(node.getProjectId())){
                    zqProjectMap.put(node.getProjectId(),node.getProjectId());
                }
            }
            for (Map.Entry<String,String> entry : zqProjectMap.entrySet()) {
                projectsList.add(projectMap.get(entry.getKey()));
            }
        }


        NodeNewschedulesFilter filter1 = new NodeNewschedulesFilter();
        List<String> projectIds = new ArrayList<>();
        Map<String, List<NodeNewschedulesModel>> nodeModelsMap = new HashMap<>();
        for (NewProjects project : projectsList) {

            projectIds.add(project.getSysId());
            List<NodeNewschedules> schedules = new ArrayList<>();
            for (NodeNewschedules node : nodeList) {
                if (project.getSysId().equals(node.getProjectId())) {
                    schedules.add(node);
                }
            }
            nodeNewschedulesMap.put(project.getSysId(), schedules);

            //推算出时间
            List<NodeNewschedulesModel> models = new ArrayList<>();
            List<NodeNewschedules> nodeList1 = nodeNewschedulesService.getNodeByProjectIdAndState(project.getSysId(), "");
            //各个节点的前置节点
            Map<String, Object> preOfNodeMap = nodeNewschedulesService.getEachNodePro(nodeList1, project);
            for (NodeNewschedules n : nodeList1) {
                NodeNewschedulesModel m = new NodeNewschedulesModel();
                //对象复制n->m
                BeanUtils.copyProperties(n, m);
                models.add(m);
            }
            //推算计划时间
            models = planTimeReckonService.reckonPlanTime(models, preOfNodeMap);
            nodeModelsMap.put(project.getSysId(), models);
        }
        filter1.setProjectIds(projectIds);
        filter1.setType("1");
        List<NodeNewschedules> bigNodes = nodeNewschedulesService.queryByFilter(filter1);
        for (NodeNewschedules bigNode : bigNodes) {
            if (!bigNodeMap.containsKey(bigNode.getNodeId())) {
                bigNodeMap.put(bigNode.getNodeId(), bigNode);
            }
        }

        Map<String, Object> map = new HashMap<>();
        if (projectsList != null) {
            for (NewProjects n : projectsList) {
                List<NodeNewschedules> stateBigNodes = bigNodeStateNeedMap.get(n.getSysId());

                List<NodeNewschedules> resList = new ArrayList<>();

                List<NodeNewschedulesModel> list0 = nodeModelsMap.get(n.getSysId());
                Map<String, NodeNewschedulesModel> modelHashMap = new HashMap<>();
                for (NodeNewschedulesModel model1 : list0) {
                    if (!modelHashMap.containsKey(model1.getSysId())) {
                        modelHashMap.put(model1.getSysId(), model1);
                    }
                }

                List<NodeNewschedules> list = nodeNewschedulesMap.get(n.getSysId());
                for (NodeNewschedules node : list) {
                    //如果大节点是确认不需要的，则同理小节点也不需要
                    boolean flag = true;
                    if(ObjectUtils.isBlank(stateBigNodes)){
                        break;
                    }
                    for (NodeNewschedules stateBigNode : stateBigNodes) {
                        if(stateBigNode.getNodeId().equals(node.getNodeIds())){
                            flag = false;
                            break;
                        }
                    }
                    if(flag){
                        continue;
                    }
                    if ("1".equals(node.getStatus())) {
                        Double progress = progress(node.getPlanBeginDate(), node.getPlanTime());
                        //将double保留三位小数
                        BigDecimal b = new BigDecimal(progress);
                        progress = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        node.setProgress(progress);
                        System.out.println("节点完成进度" + progress + "========");
                        int i = node.getNodeId().indexOf(".");
                        if (i > 0) {
                            String newStr = node.getNodeId().substring(0, i);
                            List<NodeNewtemplet> nodeNewtempletList = nodeNewtempletService.queryByNodeFilter(newStr);
                            if (nodeNewtempletList.size() != 0) {
                                NodeNewtemplet nodeNewtemplet = nodeNewtempletList.get(0);
                                node.setNodeFilter(nodeNewtemplet.getNodeFilter());
                            }
                        }
                        node.setFactFinishDate("计划:" + modelHashMap.get(node.getSysId()).getPlanEndTime());
                    } else if ("0".equals(node.getStatus())) {
                        node.setPlanBeginDate("计划:" + modelHashMap.get(node.getSysId()).getPlanBeginTime());
                        node.setFactFinishDate("计划:" + modelHashMap.get(node.getSysId()).getPlanEndTime());
                    }
                    //小节点
                    if ("2".equals(node.getType())) {
                        node.setIsDelay(bigNodeMap.get(node.getNodeIds()).getNodeName());
                        resList.add(node);
                    }
                }
                map.put(n.getName(), resList);
            }
        }
        Map<String,Object> resultMap = new HashMap<>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if(ObjectUtils.isNotBlank(entry.getValue())){
                resultMap.put(entry.getKey(),entry.getValue());
            }
        }
        int myTaskNum = (int) WebUtils.getSessionAttribute(request, "myTaskNum");
        int quetionNum = (int) WebUtils.getSessionAttribute(request, "quetionNum");
        model.addAttribute("myTaskNum", myTaskNum);
        model.addAttribute("quetionNum", quetionNum);

        int myTackTaskNum = (int) WebUtils.getSessionAttribute(request, "myTackTaskNum");
        model.addAttribute("myTackTaskNum", myTackTaskNum);

        //待办任务个数
//        int nodeCount = (int) WebUtils.getSessionAttribute(request, "nodeCount");
//        model.addAttribute("nodeCount", nodeCount);

        NodeNewschedulesFilter nodeNewschedulesFilter = new NodeNewschedulesFilter();
        nodeNewschedulesFilter.setOperatorUser(bnpUser.getName());
        nodeNewschedulesFilter.setOperatorPhone(bnpUser.getPhone());
        //进行中的小节点个数
        double totalPage12 = (double) nodeNewschedulesService.queryListByFilterZong(nodeNewschedulesFilter).size();
        model.addAttribute("nodeCount", (new Double(totalPage12)).intValue());
        //保存更新nodeCount
        WebUtils.setSessionAttribute(request, "nodeCount", (new Double(totalPage12)).intValue());

        model.addAttribute("map", resultMap);
        return "/modules/OwnerUnit/owner_project";
    }

    /**
     * 计算当前时间与计划时间之间的进度
     *
     * @param beginDate 开始日期
     * @param planDate  计划完成天数
     * @return
     */
    public Double progress(String beginDate, String planDate) {
        try {
            int num = Integer.parseInt(planDate);

            Date begin = sdf.parse(beginDate);
            ArrayList<String> arrayList = new ArrayList<>();
            //计算节点计划工作日后的日期
            Date date = HolidayUtils.getScheduleActiveDate(begin, arrayList, num);
            //计算当前日期相对于计划时间的百分比想·
            Double d = (double) (new Date().getTime() - begin.getTime()) / (double) (date.getTime() - begin.getTime());
            return d;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

}
